package com.datastructure.test.maxlengthofcontinuousserialinarray;

import java.util.Arrays;

public class MaxLengthOfContinuousSerialInArray {

    public static void main(String[] args) {
        MaxLengthOfContinuousSerialInArray maxLengthOfContinuousSerialInArray = new MaxLengthOfContinuousSerialInArray();
        int[] data = {100,4,200,1,3,2};
        int mls = maxLengthOfContinuousSerialInArray.MLS(data);
        System.out.println(mls);
    }

    public int MLS(int[] arr) {
        if (arr == null || arr.length == 0)
            return 0;
        int longest = 1;//记录最长的有序序列
        int count = 1;//目前有序序列的长度
        //先对数组进行排序
        Arrays.sort(arr);
        for (int i = 0; i < arr.length-1; i++) {
            //跳过重复的
            if (arr[i] == arr[i + 1])
                continue;
            //比前一个大1，可以构成连续的序列，count++
            if ((arr[i] - arr[i + 1]) == -1) {
                count++;
            } else {
                //没有比前一个大1，不可能构成连续的，
                //count重置为1
                count = 1;
            }
            //记录最长的序列长度
            longest = Math.max(longest, count);
        }
        return longest;
    }
}
